package com.itfreer.data.syn.http;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;

import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itfreer.data.syn.DataSynItemService;
import com.itfreer.utils.http.HeaderUtils;
import com.itfreer.utils.json.CustomDateFormat;
import com.itfreer.utils.json.JsonUtils;

/**
 * 定义数据同步通用http接口
 */
@Component("HttpDataSynItemService")
public class HttpDataSynItemService implements DataSynItemService {

	@Override
	@SuppressWarnings("unchecked")
	public String add(Object entity, String para) {
		if (para == null || para.equals("")) {
			return "参数错误，需提供url地址！";
		}
		Map<String, Object> map = JsonUtils.toBean(para, Map.class);
		String url = map.get("url").toString();

		Boolean isSSL = false;
		if (url.startsWith("https://")) {
			isSSL = true;
		}
		Client client;
		try {
			client = HeaderUtils.buildClient(isSSL);
			WebTarget target = client.target(url + "/add");
			Builder builder = target.request();
			if (map.keySet().size() > 1) {
				MultivaluedMap<String, Object> headers = new MultivaluedHashMap<String, Object>();
				for (String key : map.keySet()) {
					if (!key.equals("url")) {
						headers.add(key, map.get(key));
					}
				}
				builder = builder.headers(headers);
			}
			Response response = builder.buildPost(Entity.json(entity.toString())).invoke();
			if (response.getStatus() == 200) {
				String resultJson = response.readEntity(String.class);
				if (resultJson == null || resultJson.equals("")) {
					return null;
				}
				String code = getCodeString(resultJson);
				if (code != null && code.equals("-1")) {
					return null;
				} else {
					return getMsgString(resultJson);
				}
			} else {
				return "url访问失败";
			}
		} catch (KeyManagementException e1) {
			return e1.getMessage();
		} catch (NoSuchAlgorithmException e1) {
			return e1.getMessage();
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public String delete(String guid, String para) {
		if (para == null || para.equals("")) {
			return "参数错误，需提供url地址！";
		}
		Map<String, Object> map = JsonUtils.toBean(para, Map.class);
		String url = map.get("url").toString();

		Boolean isSSL = false;
		if (url.startsWith("https://")) {
			isSSL = true;
		}
		Client client;
		try {
			client = HeaderUtils.buildClient(isSSL);
			WebTarget target = client.target(url + "/delete/" + guid);
			Builder builder = target.request();
			if (map.keySet().size() > 1) {
				MultivaluedMap<String, Object> headers = new MultivaluedHashMap<String, Object>();
				for (String key : map.keySet()) {
					if (!key.equals("url")) {
						headers.add(key, map.get(key));
					}
				}
				builder = builder.headers(headers);
			}
			Response response = builder.buildDelete().invoke();
			if (response.getStatus() == 200) {
				String resultJson = response.readEntity(String.class);
				if (resultJson == null || resultJson.equals("")) {
					return null;
				}
				String code = getCodeString(resultJson);
				if (code != null && code.equals("-1")) {
					return null;
				} else {
					return getMsgString(resultJson);
				}
			} else {
				return "url访问失败";
			}
		} catch (KeyManagementException e1) {
			return e1.getMessage();
		} catch (NoSuchAlgorithmException e1) {
			return e1.getMessage();
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public String update(Object entity, String para) {
		if (para == null || para.equals("")) {
			return "参数错误，需提供url地址！";
		}
		Map<String, Object> map = JsonUtils.toBean(para, Map.class);
		String url = map.get("url").toString();

		Boolean isSSL = false;
		if (url.startsWith("https://")) {
			isSSL = true;
		}
		Client client;
		try {
			client = HeaderUtils.buildClient(isSSL);
			WebTarget target = client.target(url + "/update");
			Builder builder = target.request();
			if (map.keySet().size() > 1) {
				MultivaluedMap<String, Object> headers = new MultivaluedHashMap<String, Object>();
				for (String key : map.keySet()) {
					if (!key.equals("url")) {
						headers.add(key, map.get(key));
					}
				}
				builder = builder.headers(headers);
			}
			Response response = builder.buildPost(Entity.json(entity.toString())).invoke();
			if (response.getStatus() == 200) {
				String resultJson = response.readEntity(String.class);
				if (resultJson == null || resultJson.equals("")) {
					return null;
				}
				String code = getCodeString(resultJson);
				if (code != null && code.equals("-1")) {
					return null;
				} else {
					return getMsgString(resultJson);
				}
			} else {
				return "url访问失败";
			}
		} catch (KeyManagementException e1) {
			return e1.getMessage();
		} catch (NoSuchAlgorithmException e1) {
			return e1.getMessage();
		}
	}

	protected String getMsgString(String jsonObject) {
		if (jsonObject == null || jsonObject.trim().equals("")) {
			return null;
		}
		try {
			ObjectMapper mapper = new ObjectMapper();
			mapper.setDateFormat(new CustomDateFormat());
			JsonNode jsonNode = mapper.readTree(jsonObject);
			jsonNode = jsonNode.get("msg");
			return jsonNode.textValue();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	protected String getCodeString(String jsonObject) {
		if (jsonObject == null || jsonObject.trim().equals("")) {
			return null;
		}
		try {
			ObjectMapper mapper = new ObjectMapper();
			mapper.setDateFormat(new CustomDateFormat());
			JsonNode jsonNode = mapper.readTree(jsonObject);
			jsonNode = jsonNode.get("code");
			return jsonNode.textValue();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
